<template>
  <view class="safe-bottom">
    <navigation back title="个人资料" />

    <view class="page-container" v-if="token">
      <view class="user-info">
        <view class="item flex flex-middle flex-between" @click="changeAvatar">
          <view class="title"> 头像 </view>
          <view class="flex flex-middle">
            <image class="avatar" mode="aspectFill" :src="userInfo.avatar" />
            <u-icon class="icon" name="arrow-right" color="#333" size="14" />
          </view>
        </view>

        <view class="item flex flex-middle flex-between" @click="showPop(1)">
          <view class="title"> 昵称 </view>
          <view class="flex flex-middle">
            {{ userInfo.nickname }}
            <u-icon class="icon" name="arrow-right" color="#333" size="14" />
          </view>
        </view>

        <view class="item flex flex-middle flex-between" @click="showPop(2)">
          <view class="title"> 性别 </view>
          <view class="flex flex-middle">
            <text>
              {{
                userInfo.sex == 1 ? "男" : userInfo.sex == 2 ? "女" : "请选择"
              }}
            </text>
            <sex :sex="userInfo.sex" />
            <u-icon class="icon" name="arrow-right" color="#333" size="14" />
          </view>
        </view>

        <view class="item flex flex-middle flex-between" @click="showPop(3)">
          <view class="title"> 手机号 </view>
          <view class="flex flex-middle">
            {{ phoneNumber }}
            <u-icon class="icon" name="arrow-right" color="#333" size="14" />
          </view>
        </view>
      </view>

      <view class="logout logoff flex flex-middle flex-center" @click="logoff">
        注销用户
      </view>

      <view class="logout flex flex-middle flex-center" @click="logout">
        退出登录
      </view>
    </view>

    <!-- 设置弹出框 -->
    <u-popup
      round="16"
      mode="center"
      zIndex="998"
      :show="show"
      @touchmove.native.stop.prevent=""
    >
      <view class="popup">
        <view class="title text-center">
          修改{{
            type == 1 ? "昵称" : type == 2 ? "性别" : type == 3 ? "手机号" : ""
          }}
        </view>

        <view class="form-item flex flex-middle" v-if="type == 1">
          <view class="form-title"> 昵称 </view>
          <input class="flex-1" placeholder="请输入昵称" v-model="nickname" />
        </view>

        <view class="form-item flex flex-middle" v-else-if="type == 2">
          <view class="form-title"> 性别 </view>
          <u-radio-group placement="row" class="flex flex-right" v-model="sex">
            <u-radio label="男" name="1" />
            <u-radio label=" 女" name="2" class="woman" />
          </u-radio-group>
        </view>

        <view v-else-if="type == 3">
          <view class="form-item flex flex-middle">
            <view class="form-title"> 手机号 </view>
            <input
              class="flex-1"
              placeholder="请输入手机号"
              maxlength="11"
              type="number"
              v-model="mobile"
            />
          </view>
          <view class="form-item flex flex-middle">
            <view class="form-title"> 验证码 </view>
            <input
              class="flex-1"
              placeholder="请输入验证码"
              type="number"
              maxlength="6"
              v-model="code"
            />
            <view
              class="get-code flex flex-middle flex-center"
              @click="getCode"
            >
              <text v-if="!sendCodeLoad && expireTime == null && !again">
                获取验证码
              </text>

              <u-loading-icon v-else-if="sendCodeLoad" />

              <text style="color: #999" v-else-if="!again">
                重新获取（{{ expireTime }}s）
              </text>

              <text v-else>重新发送</text>
            </view>
          </view>
        </view>

        <view class="btn-view flex flex-middle flex-between">
          <view
            class="cancel-btn flex flex-middle flex-center"
            @click="show = false"
          >
            取消
          </view>
          <view class="submit-btn flex flex-middle flex-center" @click="submit">
            确定
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { mapGetters } from "vuex";
import { sendCode, uploadFile } from "@/api/common";
import { bindPhone, editUser } from "@/api/auth";

export default {
  data() {
    return {
      show: false,
      type: 0,
      sendCodeLoad: false,
      expireTime: null,
      nickname: "",
      mobile: "",
      code: "",
      sex: 0,
      avatar: "",
      again: false,
      timer: null,
    };
  },
  computed: {
    ...mapGetters(["userInfo", "codeEndTime", "token"]),
    phoneNumber() {
      const left = this.userInfo?.phone.slice(0, 3);
      const right = this.userInfo?.phone.slice(7, 11);
      return `${left}****${right}`;
    },
  },
  watch: {
    show() {
      this.mobile = "";
      this.code = "";
      this.nickname = "";
      this.sex = this.userInfo?.sex + "";
      this.again = false;
    },
  },
  onLoad() {
    if (this.codeEndTime) this.checkTime();
  },
  methods: {
    async editUser(type) {
      const params = { ...this.userInfo };
      params[type == 1 ? "nickname" : type == 2 ? "sex" : "avatar"] =
        this[type == 1 ? "nickname" : type == 2 ? "sex" : "avatar"];
      this.$loading();
      const { code } = await editUser({
        ...params,
        sex: +params.sex,
      });
      this.$loading.close();
      return code == 200;
    },
    async submit() {
      let status = false;
      switch (this.type) {
        case 1:
          // 昵称
          if (!this.nickname.length) return this.$toast("请输入用户昵称");
          status = await this.editUser(this.type);
          if (!status) return;
          break;
        case 2:
          // 性别
          if (!this.sex) return this.$toast("请选择用户性别");
          status = await this.editUser(this.type);
          if (!status) return;
          break;
        case 3:
          // 手机号
          if (!uni.$u.test.mobile(this.mobile + ""))
            return this.$toast("请输入正确的手机号");
          if (!uni.$u.test.code(this.code + ""))
            return this.$toast("请输入正确的验证码");

          this.$loading();
          const { data } = await bindPhone({
            captcha: this.code,
            phone: this.mobile,
          });
          this.$loading.close();
          if (!data) return;
          break;
      }
      this.$toast("修改成功");
      this.$loading();
      await this.$store.dispatch("getUserInfo");
      this.$loading.close();
      this.show = false;
    },
    checkTime() {
      const now = new Date() * 1;
      if (this.codeEndTime > now) {
        this.expireTime = ((+this.codeEndTime - now) / 1000).toFixed(0);
        this.startTime();
      }
    },
    async getCode() {
      if (this.sendCodeLoad || this.expireTime !== null) return;
      if (!uni.$u.test.mobile(this.mobile + ""))
        return this.$toast("请输入正确的手机号");
      // 验证通过
      this.again = false;
      this.sendCodeLoad = true;
      const { data } = await sendCode({ phone: this.mobile + "" });
      this.sendCodeLoad = false;
      if (!data) return;
      this.expireTime = +data.expireTime;
      this.$store.dispatch("saveCodeEndTime", +data.expireTime);
      this.startTime();

      // 测试
      this.code = data.code;
    },
    startTime() {
      this.timer = setInterval(() => {
        this.expireTime--;
        if (!this.expireTime) {
          this.expireTime = null;
          this.again = true;
          clearInterval(this.timer);
          this.timer = null;
        }
      }, 1000);
    },
    async logoff() {
      const res = await this.$dialog({
        showCancel: true,
        title: "确认注销",
        content: "注销后用户数据将清除，您确认要注销吗？",
      });
      if (!res) return;
      this.$store.dispatch("logoff");
    },
    async logout() {
      const res = await this.$dialog({
        showCancel: true,
        content: "确认退出当前登录？",
      });
      if (!res) return;
      this.$store.dispatch("logout");
    },
    showPop(type) {
      this.type = type;
      this.show = true;
    },
    changeAvatar() {
      uni.chooseImage({
        count: 1,
        sourceType: ["album"],
        success: async ({ tempFilePaths }) => {
          this.$loading();
          const { data, code } = await uploadFile({
            filePath: tempFilePaths[0],
            name: "multipart",
            formData: {
              model: "user",
              pid: "7",
            },
          });
          this.$loading.close();
          if (code == 200) {
            this.avatar = data.url;
            const status = await this.editUser(0);
            if (status) {
              this.$loading();
              await this.$store.dispatch("getUserInfo");
              this.$loading.close();
              this.$toast("修改成功");
            }
          }
        },
      });
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .u-transition {
  z-index: 997 !important;
}

.logout {
  background: #333;
  height: 42px;
  border-radius: 42px;
  color: #fff;
  margin: 16px 16px 0;
}

.logoff {
  background: #eee !important;
  color: #ea473f !important;
}

.popup {
  padding: 16px;
  width: 76vw;

  .form-item {
    border-bottom: 1px solid #efefef;
    height: 50px;
  }

  .get-code {
    width: 120px;
    height: 100%;
    border-left: 1px solid #efefef;
    color: #31bc4e;
  }

  .woman {
    margin-left: 16px;
  }

  input {
    font-size: 14px;
  }

  .form-title {
    width: 50px;
  }

  .title {
    font-size: 16px;
    color: #333;
    margin-bottom: 20px;
  }

  .btn-view {
    margin-top: 50px;
  }

  .submit-btn,
  .cancel-btn {
    background: #31bc4e;
    border-radius: 16px;
    height: 30px;
    width: 48%;
    color: #fff;
  }

  .cancel-btn {
    background: #eee !important;
    color: #333 !important;
  }
}

.user-info {
  padding: 0 16px 20px;

  .item {
    height: 66px;
    border-bottom: 1px solid #efefef;
    color: #323232;

    .avatar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
    }

    text {
      margin-right: 4px;
    }

    .icon {
      margin-left: 4px;
    }

    .title {
      color: #666;
    }
  }
}
</style>